package com.guoyan.blockchain.controller;

import com.guoyan.blockchain.common.response.BaseResponse;
import com.guoyan.blockchain.service.IBaseService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

/**
 * @author yeym
 */
@RestController
public class SystemController  {
    @Resource
    private IBaseService baseService;

    @PostMapping("/createChannel/{channelName}")
    public BaseResponse createChannel(@PathVariable String channelName) {
//        ChannelInfo channelInfo = channelInfoDao.findByNameAndIsDeletedFalse(channelName);
//        if (channelInfo == null) {
//            channelInfo = new ChannelInfo();
//            channelInfo.setName(channelName);
//            channelInfo.setIsActive(true);
//            channelInfo.setIsDeploy(true);
//            channelInfo.setIsDeleted(false);
//            channelInfoDao.save(channelInfo);
            if (baseService.createChannel(channelName)) {
                return BaseResponse.successful;
            } else {
                return BaseResponse.channelCreated;
            }
//        } else {
//            return BaseResponse.channelCreated;
//        }
    }

    @PostMapping("/deploy/{chainCodeName}/{version}")
    public BaseResponse deployInstantiateChainCode(@PathVariable String chainCodeName, @PathVariable Integer version, String channelName) {
//        ChainCodeInfo chainCodeInfo = chainCodeDao.findByNameAndIsDeletedFalse(chainCodeName);
//        if (chainCodeInfo == null || !chainCodeInfo.getVersion().equals(version)) {
//            chainCodeInfo = new ChainCodeInfo();
//            chainCodeInfo.setName(chainCodeName);
//            chainCodeInfo.setVersion(version);
//            chainCodeInfo.setIsDeleted(false);
            if (baseService.deployChainCode(chainCodeName, version, channelName)) {
                return BaseResponse.successful;
            } else {
                return BaseResponse.error;
            }
//        } else {
//            return BaseResponse.chinCodeDeployed;
//        }
    }

    @PostMapping("/newPeer/{ip}/{name}")
    public BaseResponse joinNewPeer(@PathVariable String ip, @PathVariable String name, String channelName) {
        return baseService.joinNewPeer(ip, name, channelName);
    }

    @GetMapping("/peers")
    public BaseResponse getPeers(){
        return BaseResponse.successful(baseService.getPeers());
    }
}
